"""
1.准备pygame开发环境,窗口尺寸，标题
    准备背景图，蛇头

2.while true:
   a.处理用户输入事件
   b.处理游戏逻辑
   a.渲染界面
   a.控制选软速度fps
"""
import pygame
import time
import random

#初始化
pygame.init()
pygame.mixer.init()

screen_width = 1280
screen_height = 720
color_gary = (210,210,210)
color_whilt = (255,255,255)
color_blue = (0,0,255)
block_size = 40

kt = pygame.mixer.music.load("res/kait.mp3")
pygame.mixer.music.play()


#方向字典
DIRECTION_DICT = {
    pygame.K_UP:(0,-block_size),  #上
    pygame.K_RIGHT:(block_size,0),  #右
    pygame.K_DOWN:(0,block_size),  #下
    pygame.K_LEFT:(-block_size,0),  #左
}
head_dict = {
            pygame.K_UP:90,
            pygame.K_RIGHT:0,
            pygame.K_DOWN:90,
            pygame.K_LEFT:0
}

class Snake:
    def __init__(self):
        self.direction = pygame.K_RIGHT
        self.snake_body = [
            pygame.Rect(5*block_size,3*block_size,block_size,block_size),
            pygame.Rect(4*block_size,3*block_size,block_size,block_size),
            pygame.Rect(3*block_size,3*block_size,block_size,block_size),
            pygame.Rect(2*block_size,3*block_size,block_size,block_size)
        ]
        head_image = pygame.image.load("res/ikun.gif")
        self.snake_head_image = pygame.transform.scale(head_image,(block_size,block_size))
        body_image = pygame.image.load("res/ikun1.gif")
        self.snake_body_image = pygame.transform.scale(body_image,(block_size,block_size))
    
    def draw(self,screen):
        #蛇身体
        for node in self.snake_body[1:]:
            """pygame.draw.rect(screen,color_whilt,node,border_radius=50)"""
            body_image = pygame.transform.rotate(self.snake_body_image,head_dict[self.direction])
            screen.blit(body_image,(node.x,node.y))
        #绘制蛇头
        head: pygame.Rect = self.snake_body[0]
        head_image = pygame.transform.rotate(self.snake_head_image,head_dict[self.direction])
        screen.blit(head_image,(head.x,head.y))
        
            
    def update_direction(self,new_dir):
        #不能原地掉头
        LR = (pygame.K_LEFT,pygame.K_RIGHT)
        if self.direction in LR and new_dir in LR:
            return
        ud = (pygame.K_UP,pygame.K_DOWN)
        if self.direction in ud and new_dir in ud:
            return
        #符合条件，更新方向
        self.direction = new_dir
        
    """def is_direction_enable(self,)"""
            
    def move(self):
        #蛇头复制一份
        new_node = self.snake_body[0].copy()
        #王前进方向移动一格
        new_move = DIRECTION_DICT[self.direction]
        new_node.x += new_move[0]
        new_node.y += new_move[1]
        #穿墙
        if new_node.x>=screen_width:
            new_node.x-=screen_width
        if new_node.x<0:
            new_node.x+=screen_width
        if new_node.y>=screen_height:
            new_node.x-=screen_height
        if new_node.y<0:
            new_node.y+=screen_height
        #新蛇头放前面
        self.snake_body.insert(0,new_node)
        #吧蛇尾移除
        self.snake_body.pop() #索引不传参，默认删除最后一个元素
        
    def grow(self):
        #蛇尾复制一份
        new_node = self.snake_body[-1].copy()
        print(new_node)
        #添加新的节点到尾部
        self.snake_body.append(new_node)
        

            
class Food:
    def __init__(self,node):
        self.node = node
        food_image = pygame.image.load("res/da.png")
        self.food_image = pygame.transform.scale(food_image,(block_size,block_size))
        
        
    def draw(self,screen):
        """pygame.draw.rect(screen,color_blue,self.node)"""
        screen.blit(self.food_image,(self.node.x,self.node.y))
    
    #注解，静态函数，可直接用类名调用(类名调用，类名调用，类名调用)
    @staticmethod  
    def gen_foof_position(snake:Snake):
        """根据屏幕大小，蛇身生成新的食物

        Args:
            snake (Snake): 蛇对象
        """
        while True:
            x = random.randint(0,screen_width//block_size-10)
            y = random.randint(0,screen_height//block_size-10)
            new_food_node = pygame.Rect(x*block_size,y*block_size,block_size,block_size)
            if new_food_node not in snake.snake_body:
                return new_food_node
        
        
class Game:
    def __init__(self):
        #设置窗口大小，获取surface(渲染)
        self.screen = pygame.display.set_mode(size=(screen_width,screen_height))

        #设置标题
        pygame.display.set_caption("贪吃蛇ikun版v1.0")
        #设置图标
        icon = pygame.image.load("res/food.gif")
        pygame.display.set_icon(icon)
        #加载背景图
        bg_image = pygame.image.load("res/bjb.png")
        self.bg_image = pygame.transform.scale(bg_image,(screen_width,screen_height))
        #结束图
        over_image = pygame.image.load("res/body.jpg")
        self.over_image = pygame.transform.scale(over_image,(10*block_size,10*block_size))
        
        
        
    def start(self):
        #clock
        clock = pygame.time.Clock()
        snake = Snake()
        food = Food(Food.gen_foof_position(snake))
        is_game_over = False

        while True:
            #处理事件，获取用户的输入事件
            event_list = pygame.event.get()
            #解析处理所有事件
            #even.type 用户输入的事件  event.key 保存按下或抬起的按键
            for event in event_list:
                if event.type == pygame.QUIT:
                    print("点击了关闭")
                    pygame.display.quit()
                    exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        print("向上")
                        snake.update_direction(pygame.K_UP)
                    elif event.key == pygame.K_RIGHT:
                        print("向右")
                        snake.update_direction(pygame.K_RIGHT)
                    elif event.key == pygame.K_DOWN:
                        print("向下")
                        snake.update_direction(pygame.K_DOWN)
                    elif event.key == pygame.K_LEFT:
                        print("向左")
                        snake.update_direction(pygame.K_LEFT)
                    elif event.key == pygame.K_ESCAPE:
                        print("关闭")
                        exit()
            
            if not is_game_over:
                #处理游戏逻辑
                snake.move()
                #遇到食物，吃掉食物
                snake_head = snake.snake_body[0]
                if snake_head == food.node:
                    #吃掉食物，刷新食物
                    food = Food(Food.gen_foof_position(snake))
                    pygame.mixer.music.load("res/ji.mp3")
                    pygame.mixer.music.play()
                    #蛇身体边长
                    snake.grow()
                #碰到自己
                if snake_head in snake.snake_body[1:]:
                    pygame.mixer.music.load("res/shuangjie_ji.mp3")
                    pygame.mixer.music.play(0)
                    
                    is_game_over = True
                    
                     
            #渲染界面
            self.screen.blit(self.bg_image,(0,0)) #背景图
            for y in range(0,screen_height,block_size):
                start = (0,y)
                end = (screen_width,y)
                pygame.draw.line(self.screen,color_gary,start,end)  #绘制横线
            for x in range(0,screen_width,block_size):
                start = (x,0)
                end = (x,screen_height)
                pygame.draw.line(self.screen,color_gary,start,end)  #绘制竖线
        
            #绘制蛇身
            snake.draw(self.screen)
        
            #绘制食物
            food.draw(self.screen)
            
            #绘制得分与fps
            fps = clock.get_fps()
            self.show_text("FPS:{:.2f}".format(fps),20,screen_width - 150,50)
            
            #根据游戏是否结束渲染文字
            if is_game_over:
                self.screen.blit(self.over_image,(200,10))
            
    
            pygame.display.flip() #执行最终渲染
            #设定FPS
            clock.tick(8)
            
    def show_text(self,text,font_size,x,y):
        font1 = pygame.font.SysFont("SimHei",font_size)
        text = font1.render(text,True,color_blue)
        self.screen.blit(text,(x,y))
        
            
            

game = Game()
game.start()

